<template>
  <q-page class="wrapBox" v-loading="loading">
      <div class="nav">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>
            <el-image src="/svgs/algManagementIcon.svg" style="width: 17px;margin-top: 2px" fit />
          </el-breadcrumb-item>
          <el-breadcrumb-item>算法服务</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ name: 'alg-manage' }">算法管理</el-breadcrumb-item>
          <el-breadcrumb-item><span style=" color: #333;">新建算法</span></el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="userData">
        <div class="title">新增算法</div>
        <div class="contentBox">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="120px"
            class="demo-ruleForm typeBox"
            style="max-width: 65%;"
            status-icon>
            <el-form-item label="算法名称：" prop="title">
              <el-input :class="[existsState == false ? 'titleBox' : 'titleBox errorBorder']" v-model.trim="ruleForm.title"
                        placeholder="请输入算法名称" @input="changeBoxState" @blur="dataExist()" @keyup.enter="dataExist()" />
              <transition name="el-fade-in-linear">
                <i v-if="existsState == true"
                   style=" font-style: initial;color:#ff5656;font-size: 12px;height: 0px;line-height: 20px;">该名称已存在</i>
              </transition>
            </el-form-item>
            <el-form-item label="描述：" prop="description">
              <el-input
                v-model.trim="ruleForm.description"
                type="textarea"
                placeholder="内容描述"
                show-word-limit
                :rows="5"
                maxlength="100" />
            </el-form-item>
            <el-form-item label="代码来源：" prop="sources">
              <el-radio-group v-model="ruleForm.sources">
                <el-radio-button label="exercise">git仓库</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="代码仓库：" prop="git_vendor">
              <el-radio-group v-model="ruleForm.git_vendor" @click.stop>
                <el-radio-button label="github" @click="verifyUser('github', $event)">Github</el-radio-button>
                <el-radio-button label="gitlab" @click="verifyUser('gitlab', $event)">Gitlab</el-radio-button>
                <el-radio-button label="bitbucket" @click="verifyUser('bitbucket', $event)">Bitbucket</el-radio-button>
                <el-radio-button label="gitee">Gitee</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="授权:" v-if="giteeCheck.is_authorized == false && ruleForm.git_vendor !== 'gitee'">
              <el-button plain type="primary" size="small" @click="toAuthorization()">
                去授权
              </el-button>
              <i style=" font-style: initial;color:#ff5656;font-size: 12px;height: 0px;line-height: 0px;margin-left: 5px;">{{ ruleForm.git_vendor }}尚未授权，请先进行授权操作</i>
              <embed>
            </el-form-item>
            <el-form-item label="是否有私有仓库:" v-if="ruleForm.git_vendor === 'gitee'">
              <el-switch
                class="switchStyle"
                v-model="ruleForm.git_is_public"
                active-text="无"
                inactive-text="有" />
            </el-form-item>
            <el-form-item label="用户名：" prop="git_user" v-if="ruleForm.git_is_public == false && ruleForm.git_vendor === 'gitee'">
              <el-input v-model.trim="ruleForm.git_user" placeholder="请输入仓库用户名" />
            </el-form-item>
            <el-form-item label="密码：" prop="git_password" v-if="ruleForm.git_is_public == false && ruleForm.git_vendor === 'gitee'">
              <el-input v-model.trim="ruleForm.git_password" placeholder="请输入仓库密码" />
            </el-form-item>
            <el-form-item label="Git地址：" prop="git_uri">
              <el-input v-model.trim="ruleForm.git_uri" placeholder="path:/" />
            </el-form-item>
            <el-form-item label="revision：" prop="git_version">
              <el-input v-model.trim="ruleForm.git_version" placeholder="请输入分支名称" />
            </el-form-item>
          </el-form>
        </div>
        <div class="row" style="justify-content: end;margin-top: 10px;background-color: #fff;padding: 10px 0 ">
          <el-button @click="resetForm(ruleFormRef)" style="background-color: #fff!important;">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            新增
          </el-button>
        </div>
      </div>
  </q-page>
</template>

<script setup lang="ts">
import { ref, reactive, watch, shallowRef, onUnmounted, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus'
import { createModelData, titleExist, checkUser, giteeAuthorize } from 'src/api/model'
import { ElMessageBox, ElMessage } from 'element-plus'
const router = useRouter()
const loading = ref(false)
const projectId = router.currentRoute.value.params.project_id
const ruleFormRef = ref<FormInstance>()
interface useInfoModel {
  title: string;
  description: string;
  sources: string;
  git_version: string;
  git_vendor: string;
  git_uri: string;
  type: string;
  git_is_public: boolean;
  git_user: string;
  git_password: string;
}
const ruleForm = reactive<useInfoModel>({
  title: '',
  description: '',
  git_version: '',
  sources: 'exercise',
  git_vendor: '',
  git_uri: '',
  type: 'git',
  git_is_public: true,
  git_user: '',
  git_password: '',
})
const giteeCheck = ref({
  is_authorized: true,
  authorization_request_url: ''
})
// git地址内容只能为https，不支持ssh
const checkIdCard = (rule: any, value: any, cb: any) => {
  if (value.length == 0) {
    cb(new Error('代码仓库不能为空'))
  } else {
    if (ruleForm.git_uri.includes('https') == false) {
      cb(new Error('请输入HTTPS地址'))
    }else{
      cb()
    }
  }

};

const rules = reactive<FormRules>({
  title: [
    { required: true, message: '算法名称不能为空', trigger: ['blur', 'change'] }
  ],
  sources: [
    { required: true, message: '', trigger: 'blur' }
  ],
  git_version: [
    { required: true, message: '请输入分支名称', trigger: ['blur', 'change'] }
  ],
  git_vendor: [
    { required: true, message: '代码仓库不能为空', trigger: 'change' },
  ],
  git_uri: [
    { required: true, validator: checkIdCard, trigger: ['blur', 'change'] },
  ],
  git_user: [
    { required: true, message: '私有仓库用户名不能为空', trigger: 'blur' },
  ],
  git_password: [
    { required: true, message: '私有仓库密码不能为空', trigger: 'blur' },
  ],
})

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  router.push({ name: 'alg-manage', params: { project_id: projectId } })
}
const existsState = ref(false)
function dataExist() {
  titleExist(projectId, { title: ruleForm.title }).then((res: any) => {
    existsState.value = res.data.exists
  }).catch(error => {
    console.log(error)
  })
}
function changeBoxState() {
  existsState.value = false

}
const checkName = ref('')
// 验证gitee是否有授权
function verifyUser(typeName: string, e: any) {
  if (e.target.tagName != 'INPUT') return
  checkName.value = typeName
  checkAuthorization()
}
function checkAuthorization() {
  loading.value = true
  checkUser(checkName.value).then((res: any) => {
    giteeCheck.value = res.data
  }).catch(error => {
    console.log(error)
  }).finally(() => {
    loading.value = false
  })
}

function toAuthorization() {
  loading.value = true
  giteeAuthorize(checkName.value).then((res: any) => {
    openWebsite(res.data.authorize_url)
  }).catch((res: any) => {
    console.log(res)
  }).finally(() => {
    loading.value = false
  })
}
function openWebsite(url: string) {
  let innerWidth = (window.innerWidth) / 2 - 400
  let innerHeight = (window.innerHeight) / 2 - 200
  let windowBox = window.open(
    url,
    '_blank',
    `width=800,height=500,top=${innerHeight},left=${innerWidth},centerscreen=1`
  )
  let loop: any = null
  if (!loop) {
    loop = setInterval(() => {
      if (windowBox?.closed) {
        clearInterval(loop)
        checkAuthorization()
      }
    }, 500)
  }
}
//删除对象中的空属性值
function removeEmptyProperties(obj: any) {
  for (let prop in obj) {
    if (obj[prop] == null || obj[prop] === '') {
      delete obj[prop];
    }
  }
  return obj;
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl || giteeCheck.value.is_authorized == false) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (existsState.value == true) return dataExist()
      loading.value = true;
      let data:any = removeEmptyProperties(ruleForm);
      createModelData(projectId, data).then((res) => {
        ElMessageBox.alert('新增算法成功', '提示', {
          confirmButtonText: '知道了',
          autofocus: false
        }).then(() => {
          router.push({ name: 'alg-manage', params: { project_id: projectId } })
        })
      }).finally(() => {
        console.log('success')
      }).catch(error => {
        console.log(error)
        loading.value = false
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>

<style scoped lang="scss">
.nav {
  display: flex;
  align-items: center;
  padding-left: 20px;
  cursor: pointer;
  background-color: var(--nav-bg-color);
  height: 46px;
  ::v-deep .el-breadcrumb{
    display: flex;
    align-items: center;
  }
}
.wrapBox {
  padding: 0 !important;
  .userData {
    margin: 0 20px;
    .title{
      width: 100%;
      padding: 12px;
      box-sizing: border-box;
      background-color: #fff;
      color: #333;
      font-size: 16px;
      font-weight: 500;
      text-align: left;
      line-height: 24px;
      border-bottom: 2px solid #f6f8fa;
    }
    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
      .demo-tabs{
        margin-top: 40px;
      }
    }
  }
}
//tab选项卡 start
::v-deep .el-radio-button__original-radio:checked + .el-radio-button__inner{
  background: #3d5ce41a!important;
  color: #3d5ce4!important;
}
::v-deep .el-radio-button__inner{
  width: 150px!important;
  background: #fafafa!important;
}
//end
//面包屑斜杆
::v-deep .el-breadcrumb__separator{
  font-size: 12px!important;
  color: #c9cdd4!important;
  margin-top: 2px!important;
}
//面包屑字体颜色
::v-deep .el-breadcrumb__inner{
  color: #666!important;
}
::v-deep .el-tabs__active-bar{
  display: none;
}
::v-deep .el-breadcrumb__inner.is-link, .el-breadcrumb__inner a{
  font-weight: normal!important;
}
.titleBox {
  &::v-deep .el-input__suffix {
    opacity: 0;
  }
}

.errorBorder {
  &::v-deep .el-input__wrapper {
    box-shadow: 0 0 0 1px #FF5656 inset;
  }
}
::v-deep .el-switch.is-checked ::v-deep .el-switch__core ::v-deep .el-switch__action{
  left: calc(100% - 20px);
}
::v-deep .switchStyle {
  .el-switch__core {
    width: 50px !important;
    height: 25px !important;
    border-radius: 60px;
    background: #FAFAFA;
  }
  .el-switch__action{
    background-color: #3D5CE4 !important;
    left: 5px;
  }
  .el-switch__label {
    position: absolute;
    padding-top: 1px;
    display: none;
    color: #3D5CE4;
    font-size: 10px !important;
    &--left {
      color: #3D5CE4 !important;
      z-index: 1;
      right: 1px;
    }
    &--right {
      color: #3D5CE4 !important;
      z-index: 1;
      left: 1px;
      font-size: 10px;
    }
    &.is-active {
      display: block;
    }
  }
  .el-switch__core:after {
    top: 15%;
    left: 4%;
    background-color: #3D5CE4;
  }
  &.el-switch.is-checked .el-switch__core::after {
    top: 15%;
    left: 97%;
    margin-left: -1.063rem;
    background-color: #3D5CE4;
  }
}
</style>
